package com.xiaomaoguai.fcp.pre.kepler.router.async.delay.strategy;

public class FibStrategy implements RetryStrategy {

	private final long sleepTime;

	private final long maximumWait;

	public FibStrategy(long sleepTime, long maximumWait) {
		this.sleepTime = sleepTime;
		this.maximumWait = maximumWait;
	}

	@Override
	public Long interval(int retrytimes) {
		long fib = fib(retrytimes);
		long result = sleepTime * fib;

		if (result > maximumWait || result < 0L) {
			result = maximumWait;
		}

		return result >= 0L ? result : 0L;
	}


	private long fib(long n) {
		if (n == 0L) return 0L;
		if (n == 1L) return 1L;

		long prevPrev = 0L;
		long prev = 1L;
		long result = 0L;

		for (long i = 2L; i <= n; i++) {
			result = prev + prevPrev;
			prevPrev = prev;
			prev = result;
		}

		return result;
	}

}
